
import {message, Modal} from "antd";
import {changeFormLoading, changeFormData} from "./RegForm";
import {changeConditon} from './condition';
import {fetchUsers, addOneUserByAdmin, destoryUser} from '../services/User';


export const QUERY_LATEST_USERS = "QUERY_LASTEST_USERS";
export const SHOW_USERS = "SHOW_USERS";
export const ADD_ONE_USER = "ADD_ONE_USER";
export const CHANGE_TABLE_LOADING = "CHANGE_TABLE_LOADING";
export const SHOW_USERS_FAILED = "SHOW_USERS_FAILED";
export const GET_ONE_USER = "GET_ONE_USER";



export function deleteUser(id){
  return function(dispatch, getState) {
    return destoryUser(id).then(
      () => dispatch(queryLatestUsers(getState().condition)),
      (error) => {
        Modal.error({
          title: '删除失败',
          content: '原则上永远不能够删除用户，您没有超级权限！'+error,
        });
        return;
      }
    );

  }
}

export function getUser(id){
  return function(dispatch, getState){
  }
}


function showUsersFailed(error){
  console.log(error);
}




export function queryLatestUsers(condition){
  return function (dispatch, getState) {
    let page = condition.pagination;
    let pageSize = page.pageSize;
    let skipNumber = pageSize*(page.current-1);
    let total = page.total;
    if (page.current*pageSize >= total && getState().Users.data.length > 0) {
      total = total + pageSize;
    }
    dispatch(changeConditon({pagination: {
      pageSize:　pageSize,
      total: total,
      current: page.current
    }}));

     dispatch(changeTableLoading(true));
     return fetchUsers({
       descending: "updatedAt",
       limit: pageSize,
       skip: skipNumber
     }).then (
      users => dispatch(showUsers(users, total)),
      error => dispatch(showUsersFailed(error))
    )
  }
}

function changeTableLoading(isLoading){
  return {type: CHANGE_TABLE_LOADING, isLoading}
}

function showUsers(users, total=10){
  return {type: SHOW_USERS, users, total}
}
function showUsersFailed(error){
  return {type: SHOW_USERS_FAILED, error}
}

export function addOneUser(){
  return function (dispatch, getState) {
    dispatch(changeFormLoading(true));
    dispatch(changeTableLoading(true));
    let userData = {
      username: getState().RegForm.username.value,
      password: getState().RegForm.password.value,
      email:  getState().RegForm.email.value,
    }
    return addOneUserByAdmin(userData).then (
      users => {

        dispatch(queryLatestUsers(getState().condition));
          message.success("添加成功！");
        dispatch(changeFormLoading(false));


      },
      error => {
        // message.error(error);
        dispatch(showUsersFailed(error))
      }
    )
  }
}
